/**
* Created by xinxinran on 15/9/16.
*/
const mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    commonUtil = require('./commonUtil'),
    Q = require('q'),
    daoCache = {},
    mongoHost = require('../config/mongo.json')['host.' + ((process.env.NODE_ENV || 'dev').startsWith('dev') ? 'dev' : 'prod')];

mongoose.model('gomokuUser', new Schema({
    userId : {type : String, default : ''},
    username : {type : String, default : ''},
    winTimes : {type : Number, default : 0},
    loseTimes : {type : Number, default : 0},
    score : {type: Number , default : 0},
    lastLogin : {type: Date}
}, {collection : 'gomokuUser'}));

const Dao = function (dbName) {
    const conn = mongoose.createConnection(`mongodb://${mongoHost}/${dbName}?authSource=admin`);

    this.userModel = conn.model('gomokuUser');
};

commonUtil.extendObj(Dao.prototype, {
    findByUserName : function(userNmae){
        const deferred = Q.defer();
        this.userModel.findOne({username : userNmae},  deferred.makeNodeResolver());
        return deferred.promise;
    },
    saveUser : function(userObj){
        const deferred = Q.defer();
        this.userModel.create(userObj,  deferred.makeNodeResolver());
        return deferred.promise;
    },
    updateUser : function(saveObj){
        const deferred = Q.defer();
        this.userModel.findOneAndUpdate({userId : saveObj.userId}, saveObj, deferred.makeNodeResolver());
        return deferred.promise;
    }
});

module.exports = {
    getDao : function(appName){
        let thisDao;
        appName = 'gomoku';
        if(!(thisDao = daoCache[appName])){
            thisDao = daoCache[appName] = new Dao(appName);
        }
        return thisDao;
    }
};
